package org.example.common.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConf extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtFilter jwtFilter;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                //禁用 CSRF（跨站请求伪造）保护
                .csrf().disable()
                .httpBasic().disable()
                //配置会话管理策略为 STATELESS，表示不使用 HttpSession 来管理用户会话状态。这适用于使用无状态的认证机制，例如基于令牌（Token）的认证方式
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(new NoAuthEntryPoint())
                .and()
                //对于 OPTIONS 请求方法和 "/login" 路径，允许所有用户匿名访问，无需进行身份验证
                //HttpMethod.OPTIONS 浏览器在发送跨域请求之前，会先发送一个 OPTIONS 请求来询问服务器对于实际请求是否允许跨域访问
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .antMatchers("/login/getToken").permitAll()
                .antMatchers("/login/getOpenid/*").permitAll()
                .antMatchers("/swagger-ui.html").permitAll()
                .antMatchers("/webjars/**").permitAll()
                .antMatchers("/v2/**").permitAll()
                .antMatchers("/swagger-resources/**").permitAll()
                .antMatchers("/api/v1/currency/**").permitAll()
//                .antMatchers("/userinfo/saveBank").permitAll()
                .antMatchers("/api/v1/article/*").permitAll()
                .antMatchers("/api/v1/bank/**").permitAll()
                .antMatchers("/api/v1/bonus/**").permitAll()
                .antMatchers("/doc.html").permitAll()
                .antMatchers("/userinfo/queryEnv").permitAll()
                .and()
                //对于所有其他的请求，要求用户进行身份验证，即需要登录才能访问
                .authorizeRequests().anyRequest().authenticated();
        http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
